package com.worldcup.controller;

import com.google.common.collect.Lists;
import com.worldcup.common.CommonResult;
import com.worldcup.model.TravelEvent;
import com.worldcup.model.User;
import com.worldcup.model.enums.TravelEventStatusEnum;
import com.worldcup.model.enums.TravelEventTypeEnum;
import com.worldcup.service.TravelEventService;
import com.worldcup.service.UserService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author duwan.zq
 * @date 2018/06/02
 */
@RestController
@RequestMapping("/api/java/notice")
public class NoticeController {

    private final static Logger logger = LoggerFactory.getLogger(NoticeController.class);

    @Autowired
    private TravelEventService travelEventService;

    @Autowired
    private UserService userService;

    private final static int EVENT_COUNT = 10;

    @RequestMapping("/list")
    public CommonResult listNotice(String openid){
        Assert.state(StringUtils.isNotBlank(openid), "openid is blank");
        List<TravelEvent> travelEventList = travelEventService.getTravelEventListByRec(openid, TravelEventStatusEnum.NOT_VIEW);
        if(CollectionUtils.isEmpty(travelEventList)){
            return CommonResult.buildSuccess(Lists.newArrayList());
        }

        //eventType -> openidList
        Map<Integer, Set<String>> map = new HashMap<>(4);
        travelEventList.forEach(event -> {
            Integer eventType = event.getEvent();
            String sendOpenid = event.getOpenid();
            Set<String> openidSet = map.get(eventType);
            if(openidSet == null){
                openidSet = new HashSet<>();
                map.put(eventType, openidSet);
            }
            if(openidSet.size() <= EVENT_COUNT){
                openidSet.add(sendOpenid);
            }
        });

        List<String> result = new ArrayList<>(travelEventList.size());
        map.forEach( (eventType, openidSet) -> openidSet.forEach(sendOpenid -> {
            User user = userService.getUser(sendOpenid);
            String noticeFormatter = TravelEventTypeEnum.getNoticeFormatter(eventType);
            if(noticeFormatter != null){
                result.add(MessageFormat.format(noticeFormatter, user.getWxname()));
            }
        }));

        return CommonResult.buildSuccess(result);
    }
}
